
# needs to be run with jruby
require 'java'

# requires saxon in classpath
import 'javax.xml.transform.TransformerFactory'
import 'javax.xml.transform.stream.StreamSource'
import 'javax.xml.transform.stream.StreamResult'
    
class Saxon
  attr_accessor :source
  
  # source = xsl file
  def initialize(source)
    @source = source
  end

  def to_s
    @source.to_s
  end

  # xml = uri to xml, params = hash of key/values passed to xsl stylesheet, cachePath = where to stick the cached transform
  def transform(xml, params, cachePath)
    
    factory = TransformerFactory.newInstance();
    x = factory.newTemplates(StreamSource.new(@source));
    
    transformer = x.newTransformer();
    
    # add xsl parameters    
    params.each { |key, value|
      puts "xslt parameter: #{key} = #{value}"
      transformer.setParameter(key, value);
      }

    transformer.transform(StreamSource.new(xml), StreamResult.new(cachePath));

    # return the contents of the cached transform
    contents = open(cachePath, "rb") {|io| io.read }
    contents  
  end
  
end
